/**
 * de.herberlin.sudoku.gui.SimpleAwtVisualizer
 */
package de.herberlin.sudoku.test;

import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Logger;

import de.herberlin.sudoku.Constants;
import de.herberlin.sudoku.Field;
import de.herberlin.sudoku.gui.Listener;

/**
 * @author herberlin
 * @created 03.06.2006
 */
public class SimpleAwtVisualizer extends Frame implements Listener,
		ActionListener {

	private Button[][] buttons = null;

	public SimpleAwtVisualizer(int radix) {
		super();
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				e.getWindow().dispose();
			}
		});
		int size = radix * radix;
		buttons = new Button[size][size];
		reset();
		pack();
		show();

	}

	public void setField(Field field) {

		if (field.getXPos() > buttons.length || field.getYPos()> buttons.length) {
			throw new RuntimeException("Bad field size: " + field);
		}
		buttons[field.getXPos()][field.getYPos()]
				.setLabel(field.getValue() == Constants.INT_NOT_SET ? " " : ""
						+ field.getValue());
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new SimpleAwtVisualizer(3);

	}

	private Logger logger = Logger.getLogger(getClass().getName());

	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		if (obj != null && obj instanceof Button) {
			Button b = (Button) obj;
			logger.info(b.getActionCommand() + "->" + b.getLabel());
		}

	}

	public void reset() {
		this.removeAll();
		int size = buttons.length;
		this.setLayout(new GridLayout(size, size));
		for (int x = 0; x < size; x++) {
			for (int y = 0; y < size; y++) {
				buttons[x][y] = new Button(" ");
				buttons[x][y].setActionCommand("[" + x + "," + y + "]");
				buttons[x][y].addActionListener(this);
				add(buttons[x][y]);
			}
		}
		this.doLayout();
	}
}
